package com.whf.android.jar.net.rx;

import android.annotation.SuppressLint;

import androidx.annotation.NonNull;

import com.whf.android.jar.constants.UserConstant;
import com.whf.android.jar.util.storage.LattePreference;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 请求添加Cookie(Authorization)
 *
 * @author 傅令杰
 * @date 2017/4/2
 */

public final class AddCookieInterceptor implements Interceptor {

    @NotNull
    @SuppressLint("CheckResult")
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        final Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("Content-Type", "application/json;charset=utf-8");
        Observable
                .just(LattePreference.getCustomAppProfile(UserConstant.COOKIE))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String cookie) {

                        //给原生API请求附带上WebView拦截下来的Cookie
                        builder.addHeader(UserConstant.COOKIE, cookie);
                    }
                });
        return chain.proceed(builder.build());
    }
}
